<script setup>
/**
 * & 文件引入区域
 */
import {
  selectShopInfoByCommodityId,
  AddShopCollection,
  removeShopCollection,
  isCommodityToCollection,
} from "@/server/api/shopApi";
import { getResidueByCommodityIdAPI } from "@/server/api/shopCommodity";
import { addHistoryAPI } from "@/server/api/shopCommodity";

import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

import { useUseStore } from "@/stores/user";
import { useIndexStore } from "@/stores/indexStore";
import { orderStatus } from "@/stores/payStore";

import { ToastFun } from "@/hook/toast";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 注册区
 */

/**
 * & 变量声明区
 */
const inventory = ref();
const route = useRoute();
const router = useRouter();
let CommodityInfo = ref(); // 商品数据详情
let userId = useUseStore().userId; // 用户id
let baseUrl = useUseStore().ing; // 商品数据图片基础路径
let commodityId = ref(); // 商品Id
let isCol = ref(); // 商品是否已经收藏

/**
 * & 函数区
 */
// 根据id查询实体店商品详情
const getCommodityInfoFun = async (id) => {
  ToastFun("Loading", { duration: 1000 });
  let res = await selectShopInfoByCommodityId(id);

  let data = res.data.data;

  if (res.data.code == 200) {
    ToastFun("", {});

    // 轮播图数据转对象再拼接
    // for (const i in data.commodityImgList1) {
    //   if (data.commodityImgList1[i] != null) {
    //     let ImgList = data.commodityImgList1[i].split(".");
    //     data.commodityImgList1[i] =
    //       baseUrl + ImgList[0] + "_640_360." + ImgList[1];
    //   }
    // }

    CommodityInfo.value = data;
    commodityId.value = CommodityInfo.value.commodityId;
    // console.log("商品Id", commodityId.value);
    console.log("实体店商品详情", CommodityInfo.value);
  } else {
    ToastFun("", {});
    router.back();
  }
};

// 获取是否有库存接口
const getResidueByCommodityId = async (id) => {
  const res = await getResidueByCommodityIdAPI(id);
  console.log("库存", res);
  inventory.value = res.data.data;
};

// 服务收藏新增接口
const AddShopColFun = async () => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await AddShopCollection({
    commodityId: commodityId.value,
    userId,
  });
  // console.log("服务收藏新增", res.data.data);

  if (data.code == 200) {
    ToastFun("", {});
    isCol.value = true; // 修改按钮状态
  } else {
    ToastFun("", {});
  }
};

// 校验服务是否已经被收藏接口
const isComToColFun = async (obj) => {
  let res = await isCommodityToCollection(obj);
  isCol.value = res.data.data;
  // console.log("校验服务是否已经被收藏", isCol.value);
};

// 服务收藏删除接口
const removeShopCollFun = async () => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await removeShopCollection({
    commodityId: commodityId.value,
    userId,
  });
  // console.log("服务收藏删除", res.data.data);

  if (data.code == 200) {
    ToastFun("", {});
    isCol.value = false; // 修改按钮状态
  } else {
    ToastFun("", {});
  }
};

// 跳转评论页面
const goComment = () => {
  router.push({
    path: "/comment",
    query: {
      CommodityInfo: JSON.stringify(CommodityInfo.value),
    },
  });
};

// 跳转订单页面
const goOrder = () => {
  console.log(inventory.value);
  if (inventory.value > 0) {
    // # 将公共管理库的订单类型修改为网店类型，使得页面调用对应的接口
    orderStatus().orderType = "shop";
    console.log(orderStatus().orderType);

    // # 生成实体店商品未支付订单的请求体，并且存入状态管理库
    orderStatus().shopOrderReq = {
      commodityId: CommodityInfo.value.commodityId,
      shopId: CommodityInfo.value.shopId,
      number: 1,
      transactionAmount: CommodityInfo.value.price.toString(),
      uid: userId,
    };

    console.log(CommodityInfo.value);

    // 跳转到订单页面
    router.push({
      path: "/shopOrder",
      query: {
        commodityInfo: JSON.stringify(CommodityInfo.value),
      },
    });
  }
};

//添加历史记录接口
const addHistory = async (commodityId, userId) => {
  const res = await addHistoryAPI(commodityId, userId);
  // console.log('历史记录',res.data);
};

onMounted(() => {
  getCommodityInfoFun(route.query.id); // 根据id查询实体店商品详情
  isComToColFun({ commodityId: route.query.id, userId }); // 校验服务是否已经被收藏接口
  getResidueByCommodityId(route.query.id);
  addHistory(route.query.id, useUseStore().userId);
});
</script>

<template>
  <div class="ScheduledDetail" v-if="CommodityInfo">
    <!-- 页头 -->
    <div class="top">
      <pageTop :bg="'#fff'" />
    </div>

    <div class="content">
      <!-- 标题 -->
      <div class="title">
        <div class="text">{{ CommodityInfo.commodityName }}</div>
        <div class="btn" @click="AddShopColFun" v-if="!isCol">
          {{ $t("shop.scheduledDetail.collect") }}
        </div>
        <div class="btn" @click="removeShopCollFun" v-else>
          {{ $t("shop.scheduledDetail.unCollect") }}
        </div>
      </div>

      <div class="tag">
        <div class="item">
          <img src="/images/Shop/tagIcon.png" alt="" />
          <span>{{ $t("shop.scheduledDetail.booking") }}</span>
        </div>

        <div class="item">
          <img src="/images/Shop/tagIcon.png" alt="" />
          <span>{{ $t("shop.scheduledDetail.non-refundable") }}</span>
        </div>
      </div>

      <!-- 轮播图 -->
      <div class="swiper" dir="ltr">
        <van-swipe class="my-swiper">
          <van-swipe-item v-for="(item, i) in CommodityInfo.commodityImgList1" :key="i">
            <img :src="item" alt="" />
          </van-swipe-item>
          <template #indicator="{ active, total }">
            <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
          </template>
        </van-swipe>
      </div>

      <!-- 详情 -->
      <div class="detail">
        <div :class="['title', useIndexStore().isRtl ? 'is_rtl' : '']">
          {{ $t("item.details.detail") }}
        </div>

        <div class="info">
          <div class="item">
            <div class="title">{{ $t("shop.scheduledDetail.detail") }}</div>
            <div :class="['content', useIndexStore().isRtl ? 'is_rtl' : '']">
              {{ CommodityInfo.commodityDetail }}
            </div>
          </div>

          <div class="item">
            <div class="title">{{ $t("shop.scheduledDetail.notes") }}</div>
            <div :class="['content', useIndexStore().isRtl ? 'is_rtl' : '']">
              {{ CommodityInfo.reservationInformation }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="commentBox">
      <span>{{ $t("item.details.comment") }}</span>
      <div @click="goComment">
        <img src="/images/cart/go.png" alt="" :class="[useIndexStore().isRtl ? 'trun_180' : '']" />
      </div>
    </div>

    <div class="buyBtn" @click="goOrder">
      <div class="btn" v-if="inventory > 0">{{ $t("item.details.buy") }}</div>
      <div class="btn2" v-else>{{ $t("item.details.outOfStock") }}</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.ScheduledDetail>.commentBox {
  height: 25rem;
  display: flex;
  align-items: center;
  justify-content: space-between;

  padding: 0 16rem;

  span {
    font-size: 16rem;
    font-weight: 400;
    color: rgb(51, 51, 51);
  }

  div {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 24rem;
    height: 24rem;
    line-height: 24rem;

    img {
      width: 6rem;
      height: 12rem;
    }
  }
}

.ScheduledDetail {
  min-height: 100vh;
  max-height: 100vh;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  >.top {
    padding-bottom: 4rem;
    position: sticky;
    top: 0;
    z-index: 1000;
  }

  >.content {
    padding: 16rem;

    >.name {
      font-size: 16rem;
      font-weight: 400;
      line-height: 22rem;
      color: rgba(153, 153, 153, 1);
      margin-bottom: 8rem;
    }

    >.title {
      display: flex;
      justify-content: space-between;

      >.text {
        font-size: 24rem;
        font-weight: 500;
        line-height: 34rem;
        color: rgba(51, 51, 51, 1);
      }

      >.btn {
        display: flex;
        align-items: center;
        justify-content: center;

        padding: 6rem 8rem 5rem;
        border-radius: 4rem;
        min-width: 70rem;

        font-size: 12rem;
        color: #fff;
        font-weight: 400;

        background: #642e8e;
      }
    }

    >.tag {
      display: flex;
      line-height: 16rem;
      margin-bottom: 12rem;

      >.item {
        font-size: 14rem;
        font-weight: 400;
        line-height: 20rem;
        color: rgba(102, 102, 102, 1);

        display: flex;
        align-items: center;
        margin-right: 10rem;

        >img {
          width: 16rem;
          margin: 0 4rem;
        }
      }
    }

    >.swiper {
      border-radius: 12rem;
      overflow: hidden;
      margin-bottom: 16rem;

      >.my-swiper {
        position: relative;

        img {
          width: 100%;
        }

        >.custom-indicator {
          position: absolute;
          right: 12rem;
          bottom: 12rem;

          color: #fff;
          font-size: 12rem;

          background: #828282;
          padding: 2rem 6rem;
          border-radius: 9rem;
        }
      }
    }

    >.detail {
      position: relative;
      padding-bottom: 4rem;

      >.title {
        font-size: 20rem;
        font-weight: 400;
        line-height: 28rem;
        color: rgba(51, 51, 51, 1);

        position: relative;
        padding-bottom: 20rem;
        border-bottom: 1rem solid #e6e6e6;

        &.is_rtl::before {
          left: unset;
          right: 20rem;
        }

        &::before {
          content: "";
          height: 2rem;
          width: 16rem;

          border-radius: 1rem;
          background: #642e8e;

          position: absolute;
          bottom: 16rem;
          left: 20rem;
        }
      }

      >.info {
        margin-top: 12rem;

        >.item {
          margin-bottom: 8rem;

          font-size: 14rem;
          font-weight: 400;
          line-height: 20rem;

          >.title {
            color: #999;
            margin-bottom: 2rem;
          }

          >.content {
            color: #666666;
            text-indent: 10rem;
            position: relative;
            width: max-content;

            &.is_rtl::before {
              left: unset;
              right: 3rem;
            }

            &::before {
              content: "";
              position: absolute;
              top: 8rem;
              left: 3rem;

              width: 2rem;
              height: 2rem;
              background: #666;
            }
          }
        }
      }
    }
  }

  >.comment {
    padding-bottom: 100rem;
  }

  >.buyBtn {
    position: fixed;
    z-index: 1000;
    bottom: 0;
    left: 0;
    right: 0;

    padding: 6rem 16rem 10rem;

    background: #fff;

    >.btn {
      background: #642e8e;
      padding: 8rem 0;
      border-radius: 8rem;

      font-size: 20rem;
      font-weight: 500;
      line-height: 28rem;
      color: #fff;
      text-align: center;
    }

    >.btn2 {
      background: #eee01b;
      padding: 8rem 0;
      border-radius: 8rem;
      font-size: 20rem;
      font-weight: 500;
      line-height: 28rem;
      color: #fff;
      text-align: center;
    }
  }
}
</style>
